#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : data_asve_srt_file.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/26 15:13
"""
import os
import json
import tempfile
import traceback
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtCore import QThread, pyqtSignal



class SaveSrtFileWorkerQtThread(QThread):
    """保存srt文件"""
    result = pyqtSignal(dict)
    failed = pyqtSignal(Exception)

    def __init__(self, content, parent=None):
        super(SaveSrtFileWorkerQtThread, self).__init__()
        self.datas = json.loads(content)

    def format_timestamp(self, milliseconds: float) -> str:
        """格式化时间戳，包括毫秒"""
        total_seconds = milliseconds / 1000.0  # 将毫秒转换为秒
        m, s = divmod(total_seconds, 60)
        h, m = divmod(m, 60)
        s, ms = divmod(s, 1)  # 分离秒和毫秒
        return '{:02d}:{:02d}:{:02d},{:03d}'.format(int(h), int(m), int(s), int(ms * 1000))

    def run(self):
        try:
            while True:
                folder = QFileDialog.getExistingDirectory(None, "选择文件夹")
                if folder:
                    file_path = tempfile.mktemp(suffix='.srt', dir=folder)
                    with open(file_path, 'w', encoding='utf-8') as f:
                        for data in self.datas:
                            f.write(str(data['id']) + '\n')
                            f.write(self.format_timestamp(data['start']) +'-->'+ self.format_timestamp(data['end']) + '\n')
                            f.write(data['text'] + '\n\n')
                    break
        except Exception as e:
            traceback.print_exc()
            self.failed.emit(e)